package exp07gui.tictactoe;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class TicTacToe extends JFrame implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args) {
		new TicTacToe();
	}

	final static String X = "X";
	final static String O = "O";
	final static String E = " ";
	final static int EE = 2;
	final static int XX = 1;
	final static int OO = 0;
	int turn = 0;
	int B[][] = new int[3][3];
	JButton[] btn = new JButton[9];

	public TicTacToe() {
		this.setLayout(new GridLayout(3, 3));
		for (int i = 0; i < 9; i++) {
			this.add(btn[i] = new JButton());
			btn[i].addActionListener(this);
		}
		for (int i = 0; i < 9; i++)
			B[i / 3][i % 3] = EE;
		this.setSize(300, 300);
		this.setVisible(true);

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		for (int i = 0; i < 9; i++) {
			if (e.getSource() == btn[i]) {
				++turn;
				if (turn % 2 == 0) {
					btn[i].setText(O);
					B[i / 3][i % 3] = OO;
				} else {
					btn[i].setText(X);
					B[i / 3][i % 3] = XX;
				}
				btn[i].setEnabled(false);

				if (checkWin(turn % 2)) {
					JOptionPane.showMessageDialog(null, "OX".charAt(turn % 2)
							+ " Win!");
					resetGame();
					return;

				} else if (turn == 9) {
					JOptionPane.showMessageDialog(null, "Draw");
					resetGame();
					return;
				}

				break;
			}

		}

	}

	private void resetGame() {
		for (int i = 0; i < 9; i++) {
			B[i / 3][i % 3] = EE;
			btn[i].setText(E);
			btn[i].setEnabled(true);

		}

	}

	private boolean checkWin(int x) {
		for (int i = 0; i < 3; i++)
			if (B[i][0] == x && B[i][1] == x && B[i][2] == x)
				return true;
		for (int i = 0; i < 3; i++)
			if (B[0][i] == x && B[1][i] == x && B[2][i] == x)
				return true;
		if (B[0][0] == x && B[1][1] == x && B[2][2] == x)
			return true;
		return B[0][2] == x && B[1][1] == x && B[2][0] == x;

	}

}
